﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CoreTools.Tool.Fitter
{
    public class GlobalActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult.Value == null)
                {
                    context.Result = new ObjectResult(new { code = 404, en_Msg = "Resource Not Found", msg = "未找到资源" });
                }
                else
                {
                    context.Result = new ObjectResult(new { code = 10001, en_Msg = "Request Success", msg = "接口调用成功", data = objectResult.Value });
                }
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(new { code = 404, en_Msg = "Resource Not Found", msg = "未找到资源" });
            }
            else if (context.Result is ContentResult)
            {
                //context.Result = new ObjectResult(new { code = 10001, en_Msg = "Request Success", msg = "接口调用成功", data = (context.Result as ContentResult).Content });
                //百度富文本编辑 需要注释调返回
            }
            else if (context.Result is StatusCodeResult)
            {

                context.Result = new ObjectResult(new { code = (context.Result as StatusCodeResult).StatusCode, en_Msg = "Request Failed", msg = "接口调用失败" });
            }
            else
            {
                context.Result = new ObjectResult(new { code = 405, en_Msg = "Program Error", msg = "程序报错" });
            }
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Response.Headers["Access-Control-Allow-Origin"] = "*";//解决拦截器添加后跨域不生效的问题
            if (!context.ModelState.IsValid)//验证参数的合法性问题。返回错误信息
            {
                ///模型有效性验证失败处理逻辑...比如将提示信息返回
                StringBuilder stringBuilder = new StringBuilder();
                ///模型有效性验证失败处理逻辑.....
                ///如返回错误信息,这里可自动包装
                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        stringBuilder.Append($"{ error.ErrorMessage}|");
                    }
                }

                context.Result = new ContentResult
                {
                    Content = stringBuilder.ToString(),
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "text/html;charset=utf-8"
                };
            }
        }
    }
}
